package com.rdtravel.services;

import com.rdtravel.entities.Customer;
import com.rdtravel.exceptions.CustomerAlreadyExitstException;
import com.rdtravel.exceptions.InvalidEntityException;

import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
class JPACustomersService extends JPAService implements CustomersService {
	private final PasswordEncoder passwordEncoder = new ShaPasswordEncoder();

	@Override
	public void create(Customer customer) {
		if (! validator.validate(customer).isEmpty()) {
			throw new InvalidEntityException();
		}			
		if (findByUsername(customer.getUsername()) == null) {
			customer.setPassword(passwordEncoder.encodePassword(
					customer.getPassword(), null));
			entityManager.persist(customer); 
		} else {
			throw new CustomerAlreadyExitstException();
		}
	}

	@Override
	public Customer findByUsername(String username) {
		TypedQuery<Customer> query = entityManager.createNamedQuery(
				"findCustomerByName", Customer.class);
		query.setParameter("username", username);
		try {
			return query.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		}
	}

	@Override
	public Customer findById(long id) {
		return entityManager.find(Customer.class, id);
	}
}
